<template>
  <div class="education-step">
    <div class="step-header">
      <h3>教育背景</h3>
      <p>请填写您的教育经历</p>
    </div>

    <div class="education-list">
      <div 
        v-for="(education, index) in educationList"
        :key="education.id || index"
        class="education-item"
      >
        <el-form 
          :model="education"
          :rules="rules"
          label-width="100px"
          class="education-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学校名称" prop="school_name">
                <el-input v-model="education.school_name" placeholder="请输入学校名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" prop="major">
                <el-input v-model="education.major" placeholder="请输入专业" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学历" prop="degree">
                <el-select v-model="education.degree" placeholder="请选择学历" style="width: 100%">
                  <el-option
                    v-for="option in DEGREE_OPTIONS"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="GPA" prop="gpa">
                <el-input v-model="education.gpa" placeholder="如：3.8/4.0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="start_date">
                <el-date-picker
                  v-model="education.start_date"
                  type="month"
                  placeholder="请选择开始时间"
                  style="width: 100%"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="end_date">
                <el-date-picker
                  v-model="education.end_date"
                  type="month"
                  placeholder="请选择结束时间"
                  style="width: 100%"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  :disabled="education.is_current"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-checkbox v-model="education.is_current">目前在读</el-checkbox>
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input
              v-model="education.description"
              type="textarea"
              placeholder="请输入相关描述（选填）"
              :rows="3"
            />
          </el-form-item>

          <div class="form-actions">
            <el-button @click="removeEducation(index)" v-if="educationList.length > 1">
              删除
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <div class="step-actions">
      <el-button @click="addEducation">
        <el-icon><Plus /></el-icon>
        添加教育经历
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存教育背景
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, type FormRules } from 'element-plus'
import { educationApi, type Education, DEGREE_OPTIONS } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const educationList = ref<Education[]>([])

// 表单验证规则
const rules: FormRules = {
  school_name: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  degree: [
    { required: true, message: '请选择学历', trigger: 'change' }
  ],
  start_date: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ]
}

// 监听教育背景变化，判断是否完成
watch(educationList, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const hasValidEducation = educationList.value.some(edu => 
    edu.school_name && edu.major && edu.degree && edu.start_date
  )
  emit('completed', hasValidEducation)
}

// 获取教育背景列表
const fetchEducationList = async () => {
  loading.value = true
  try {
    const response = await educationApi.getEducationList(props.resumeId)
    const data = response.data || response
    
    if (data.results && data.results.length > 0) {
      educationList.value = data.results
    } else if (Array.isArray(data) && data.length > 0) {
      educationList.value = data
    } else {
      // 如果没有数据，添加一个空的教育背景
      addEducation()
    }
  } catch (error) {
    // 如果没有数据，添加一个空的教育背景
    addEducation()
  } finally {
    loading.value = false
  }
}

// 添加教育背景
const addEducation = () => {
  educationList.value.push({
    school_name: '',
    major: '',
    degree: 'bachelor',
    start_date: '',
    end_date: '',
    is_current: false,
    gpa: '',
    description: '',
    order: educationList.value.length
  })
}

// 删除教育背景
const removeEducation = async (index: number) => {
  const education = educationList.value[index]
  
  if (education.id) {
    try {
      await educationApi.deleteEducation(props.resumeId, education.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      return
    }
  }
  
  educationList.value.splice(index, 1)
}

// 保存教育背景
const handleSave = async () => {
  saving.value = true
  try {
    for (const education of educationList.value) {
      // 跳过空的教育背景
      if (!education.school_name || !education.major) {
        continue
      }

      if (education.id) {
        // 更新
        await educationApi.updateEducation(props.resumeId, education.id, education)
      } else {
        // 创建
        const response = await educationApi.createEducation(props.resumeId, education)
        const data = response.data || response
        education.id = data.id
      }
    }

    ElMessage.success('保存成功')
    
    // 重新获取数据
    await fetchEducationList()

  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchEducationList()
})
</script>

<style lang="scss" scoped>
.education-step {
  .step-header {
    margin-bottom: 32px;

    h3 {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      color: var(--text-color-secondary);
      margin: 0;
    }
  }

  .education-list {
    .education-item {
      border: 1px solid var(--border-color-light);
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 20px;
      background: var(--bg-color);

      &:last-child {
        margin-bottom: 0;
      }

      .education-form {
        .form-actions {
          text-align: right;
          margin-top: 16px;
          padding-top: 16px;
          border-top: 1px solid var(--border-color-extra-light);
        }
      }
    }
  }

  .step-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color-extra-light);
    display: flex;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .education-step {
    .education-list {
      .education-item {
        padding: 16px;

        .education-form {
          .el-row {
            .el-col {
              margin-bottom: 16px;
            }
          }
        }
      }
    }
  }
}
</style>
